<?php
	function jara_page_start($title) {
		global $jconfig;
		session_start();
		
		$template = file_get_contents(dirname(__FILE__)."/../templates/".$jconfig->template."/header.tpl");
		
		$template = preg_replace_callback("/\[if:(pages)\]([^\[]*)\[\/if\]/is", "jara_template_if", $template);
		$template = str_replace("{blog_title}", $jconfig->settings["blog_title"], $template);
		$template = str_replace("{page_title}", $title, $template);
		$template = str_replace("{blog_url}", $jconfig->settings["blog_url"], $template);
		$template = str_replace("{menu}", jara_menu(), $template);
		$template = str_replace("{menu.ul}", jara_menu("list"), $template);
		$template = str_replace("{menu.links}", jara_menu_links(), $template);
		$template = str_replace("{menu.links.ul}", jara_menu_links("list"), $template);
		$template = str_replace("{menu.pages}", jara_menu_pages(), $template);
		$template = str_replace("{menu.pages.ul}", jara_menu_pages("list"), $template);
		$template = str_replace("{widgets}", jara_widgets(), $template);
		$template = str_replace("{year}", date("Y"), $template);
		$template = str_replace("{month}", date("F"), $template);
		$template = str_replace("{day}", date("jS"), $template);
		
		echo $template;
	}
	
	function jara_template_if($matches) {
		$if = $matches[1];
		if($if == "pages") {
			if(strpos($_SERVER["SCRIPT_FILENAME"], "admin/") === false) {
				$result = jara_db_query("select * from jara_pages where menu = '1'");
				if($result->num_rows == 0) {
					return "";
				}
				else {
					return $matches[2];
				}
			}
			else {
				return "";
			}
		}
	}
	
	function jara_micro($string) {
		return strtolower(preg_replace("/[^-a-zA-Z0-9]/", "-", $string));
	}
	
	
	function jara_write_post($id, $nf = false, $profile = true) {
		global $jconfig;
		$result = jara_db_query("select * from jara_posts where id = '$id'");
		if($result->num_rows == 0) {
			throw new JaraGeneralException("The requested post does not exist.");
		}
		$row = $result->fetch_assoc();
		if($nf == true) {
			jara_page_start($row["title"]);
		}
		$category = jara_get_category($row["categoryid"]);
		
		$template = file_get_contents(dirname(__FILE__)."/../templates/".$jconfig->template."/post.tpl");
		$template = str_replace("{blog_title}", $jconfig->settings["blog_title"], $template);
		$template = str_replace("{blog_url}", $jconfig->settings["blog_url"], $template);
		$template = str_replace("{menu}", jara_menu(), $template);
		$template = str_replace("{menu.ul}", jara_menu("list"), $template);
		$template = str_replace("{menu.links}", jara_menu_links(), $template);
		$template = str_replace("{menu.links.ul}", jara_menu_links("list"), $template);
		$template = str_replace("{menu.pages}", jara_menu_pages(), $template);
		$template = str_replace("{menu.pages.ul}", jara_menu_pages("list"), $template);
		$template = str_replace("{widgets}", jara_widgets(), $template);
		$template = str_replace("{year}", date("Y"), $template);
		$template = str_replace("{month}", date("F"), $template);
		$template = str_replace("{day}", date("jS"), $template);
		$template = str_replace("{title}", $row["title"], $template);
		$template = str_replace("{time}", date("jS F Y", $row["time"]), $template);
		$template = str_replace("{author}", $row["author"], $template);
		$template = str_replace("{permalink}", jara_permalink($row["id"], "url"), $template);
		$template = str_replace("{categoryid}", $row["categoryid"], $template);
		$template = str_replace("{category_title}", $category["title"], $template);
		$template = str_replace("{text}", $row["text"], $template);
		$template = str_replace("{category_url}", jara_category_permalink($row["categoryid"]), $template);
		
		echo $template;
		if($nf == true) {
			echo "<a name=\"comments\"></a>";
			echo "<h3>Comments</h3>";
			jara_write_comments($id);
			if(jara_comments_count($id) == 0) {
				echo "<p>There are no comments on this post.";
				if($row["allowcomments"] == 1) {
					echo " Why not leave your own?";
				}
				echo "</p>";
			}
			if($row["allowcomments"] == 1) {
?>
<h3>Leave a Comment</h3>
<form action="<?php echo jara_permalink($id, "url"); ?>" method="post">
	<table border="0">
		<input type="hidden" name="id" id="id" value="<?php echo $id; ?>" />
		<tr>
			<td><strong>Your Name:</strong></td>
			<td><input type="text" name="name" id="name" /></td>
		</tr>
		<tr>
			<td><strong>Your Website:</strong></td>
			<td><input type="text" name="website" id="website" /></td>
		</tr>
		<tr>
			<td><strong>Your Comment:</strong></td>
			<td><textarea name="comment" id="comment" cols="40" rows="4"></textarea></td>
		</tr>
		<tr>
			<td><strong>Security Question:</strong><br />What is <?php $_SESSION["var1"] = mt_rand(1, 9); echo $_SESSION["var1"]; ?> + <?php $_SESSION["var2"] = mt_rand(1, 9); $_SESSION["result"] = $_SESSION["var1"] + $_SESSION["var2"]; echo $_SESSION["var2"]; ?>?</td>
			<td><input type="text" name="security" id="security" /></td>
		</tr>
		<tr>
			<td>&nbsp;</td>
			<td><input type="submit" value="Post Comment" /></td>
		</tr>
	</table>
</form>
<br /><br />
<?php
			}
			else {
				echo "<p>Comments have been disabled for this post.</p>";
			}
			jara_page_end();
		}
		else {
			$count_comments = jara_comments_count($id);
			echo "<br /><a href=\"view.php?id=$id#comments\">$count_comments comment".(($count_comments == 1) ? "" : "s")."</a>";
			if($row["allowcomments"] == 0) {
				echo " (comments disabled)";
			}
			echo "<br /><br />";
		}
	}
	
	function jara_pp_on() {
		if(!function_exists("apache_getenv")) {
			return isset($jconfig->settings["pretty_permalink"]);
		}
		else {
			return (isset($jconfig->settings["pretty_permalink"]) || apache_getenv("PRETTY_PERMALINK") != false);
		}
	}
	
	function jara_category_permalink($categoryid) {
		global $jconfig;
		$result = jara_db_query("select * from jara_categories where categoryid = '$categoryid'");
		$row = $result->fetch_assoc();
		if(!jara_pp_on()) {
			return $jconfig->settings["blog_url"]."/category.php?id=$categoryid";
		}
		else {
			return $jconfig->settings["blog_url"]."/category/$categoryid/".jara_micro($row["title"]);
		}
	}
	
	function jara_permalink($postid, $mode = "html") {
		global $jconfig;
		$result = jara_db_query("select * from jara_posts where id = '$postid'");
		$row = $result->fetch_assoc();
		if($mode == "html") {
			if(!jara_pp_on()) {
				return "<a href=\"".$jconfig->settings["blog_url"]."/view.php?id=$postid\">".$row["title"]."</a>";
			}
			else {
				return "<a href=\"".$jconfig->settings["blog_url"]."/$postid/".jara_micro($row["title"])."\">".$row["title"]."</a>";
			}
		}
		else {
			if(!jara_pp_on()) {
				return $jconfig->settings["blog_url"]."/view.php?id=$postid";
			}
			else {
				return $jconfig->settings["blog_url"]."/$postid/".jara_micro($row["title"]);
			}
		}
	}
	
	function jara_get_category($categoryid) {
		$result = jara_db_query("select * from jara_categories where categoryid = '$categoryid'");
		return $result->fetch_assoc();
	}
	
	function jara_comments_count($postid) {
		$result = jara_db_query("select * from jara_comments where postid = '$postid'");
		return $result->num_rows;
	}
	
	
	function jara_write_comments($postid) {
		global $jconfig;
		$result = jara_db_query("select * from jara_comments where postid = '$postid' order by time desc");
		$count = $result->num_rows;
		for($i = 0; $i < $count; $i++) {
			$row = $result->fetch_assoc();
			$template = file_get_contents(dirname(__FILE__)."/../templates/".$jconfig->template."/comment.tpl");
			$template = str_replace("{website}", $row["website"], $template);
			$template = str_replace("{name}", $row["name"], $template);
			$template = str_replace("{time}", date("jS F Y", $row["time"]), $template);
			$template = str_replace("{comment}", nl2br($row["comment"]), $template);
			echo $template;
		}
	}

	function jara_write_posts($show = 10, $profile = true) {
		$result = jara_db_query("select * from jara_posts order by time desc");
		if($result->num_rows == 0) {
			throw new JaraGeneralException("No posts exist in the database.");
		}
		$id_numbers = array();
		$count = $result->num_rows;
		if($result->num_rows > $show) {
			$count = $show;
		}
		for($i = 0; $i < $count; $i++) {
			$row = $result->fetch_assoc();
			array_push($id_numbers, $row["id"]);
		}
		foreach($id_numbers as $currId) {
			jara_write_post($currId, false, $profile);
		}
	}
	
	function jara_widgets() {
		global $jconfig;
		$return = "";
		if($jconfig->settings["widget_search"] == 1) {
			$return .= jara_widget_search();
		}
		if($jconfig->settings["widget_user"] == 1) {
			$return .= jara_widget_user();
		}
		if($jconfig->settings["widget_recent_posts"] == 1) {
			$return .= jara_widget_recent_posts();
		}
		if($jconfig->settings["widget_categories"] == 1) {
			$return .= jara_widget_categories();
		}
		return $return;
	}
	
	function jara_widget_search() {
		return "<h3>Search</h3><form action=\"search.php\" method=\"post\"><input type=\"hidden\" name=\"search_action\" id=\"search_action\" value=\"term\" /><p>Search term:<input type=\"text\" name=\"term\" id=\"term\" /><input type=\"submit\" value=\"Go\" /></p></form>";
	}
	
	function jara_widget_user() {
		global $jconfig;
		if(isset($_SESSION["jara_admin"])) {
			return "<h3>User</h3><p>Welcome <strong>".$_SESSION["jara_admin"]."</strong>.<br /><a href=\"".$jconfig->settings["blog_url"]."/admin/index.php\">Admin CP</a><br /><a href=\"".$jconfig->settings["blog_url"]."/admin/logout.php\">Logout</a></p>";
		}
		else {
			return "<h3>User</h3><p>You are not logged in. Please <a href=\"".$jconfig->settings["blog_url"]."/login.php\">log in</a>.</p>";
		}
	}
	
	function jara_widget_recent_posts() {
		$return = "<h3>Recent Posts</h3>";
		$result = jara_db_query("select * from jara_posts order by time desc limit 5");
		$count = $result->num_rows;
		if($count == 0) {
			$return .= "<p>There are no posts.</p>";
		}
		else {
			$return .= "<p>";
		}
		for($i = 0; $i < $count; $i++) {
			$row = $result->fetch_assoc();
			$return .= jara_permalink($row["id"]) . "<br />";
		}
		if($count != 0) {
			$return .= "</p>";
		}
		return $return;
	}
	
	function jara_widget_categories() {
		global $jconfig;
		$return = "<h3>Categories</h3>";
		$result = jara_db_query("select * from jara_categories");
		$count = $result->num_rows;
		$return .= "<p>";
		for($i = 0; $i < $count; $i++) {
			$row = $result->fetch_assoc();
			$return .= "<a href=\"".jara_category_permalink($row["categoryid"])."\">".$row["title"]."</a> (";
			$num_posts = jara_db_query("select * from jara_posts where categoryid = '".$row["categoryid"]."'");
			$return .= $num_posts->num_rows . ")</a><br />";
		}
		$return .= "</p>";
		return $return;
	}
	
	function jara_menu_links($mode = "html") {
		global $jconfig;
		$links = array();
		$linknames = array();
		if(strpos($_SERVER["SCRIPT_FILENAME"], "admin/") === false) {
			array_push($linknames, "Homepage");
			array_push($links, "index.php");
			array_push($linknames, "Search");
			array_push($links, "search.php");
			if(!isset($_SESSION["jara_admin"])) {
				array_push($linknames, "Login");
				array_push($links, "login.php");
			}
			else {
				array_push($linknames, "Admin CP");
				array_push($links, "admin/index.php");
				array_push($linknames, "Logout");
				array_push($links, "admin/logout.php");
			}
		}
		else {
			array_push($linknames, "Visit Blog");
			array_push($links, "index.php");
			array_push($linknames, "Overview");
			array_push($links, "admin/index.php");
			if($_SESSION["jara_permissions"][0] == 1) {
				array_push($linknames, "Posts");
				array_push($links, "admin/posts.php");
			}
			if($_SESSION["jara_permissions"][1] == 1) {
				array_push($linknames, "Pages");
				array_push($links, "admin/pages.php");
			}
			if($_SESSION["jara_permissions"][2] == 1) {
				array_push($linknames, "Users");
				array_push($links, "admin/users.php");
			}
			if($_SESSION["jara_permissions"][3] == 1) {
				array_push($linknames, "Upload");
				array_push($links, "admin/upload.php");
			}
			array_push($linknames, "Logout");
			array_push($links, "admin/logout.php");
		}
		$linklist = array_combine($linknames, $links);
		$return = "";
		if($mode == "html") {
			foreach($linklist as $name => $link) {
				$return .= "<a href=\"".$jconfig->settings["blog_url"]."/$link\">$name</a><br />\r\n";
			}
		}
		else if($mode == "list") {
			$return .= "<ul>\r\n";
			foreach($linklist as $name => $link) {
				$return .= "<li><a href=\"".$jconfig->settings["blog_url"]."/$link\">$name</a></li>\r\n";
			}
			$return .= "</ul>";
		}
		return $return;
	}
	
	function jara_menu_pages($mode = "html") {
		global $jconfig;
		$links = array();
		$linknames = array();
		if(strpos($_SERVER["SCRIPT_FILENAME"], "admin/") === false) {
			$result = @jara_db_query("select * from jara_pages where menu = '1'");
			if($result) {
				for($i = 0; $i < $result->num_rows; $i++) {
					$row = $result->fetch_assoc();
					array_push($linknames, $row["title"]);
					array_push($links, "page.php?id=".$row["id"]);
				}
			}
		}
		if(count($links) != 0) {
			$linklist = array_combine($linknames, $links);
			$return = "";
			if($mode == "html") {
				foreach($linklist as $name => $link) {
					$return .= "<a href=\"".$jconfig->settings["blog_url"]."/$link\">$name</a><br />\r\n";
				}
			}
			else if($mode == "list") {
				$return .= "<ul>\r\n";
				foreach($linklist as $name => $link) {
					$return .= "<li><a href=\"".$jconfig->settings["blog_url"]."/$link\">$name</a></li>\r\n";
				}
				$return .= "</ul>";
			}
			return $return;
		}
		else {
			return "";
		}
	}
	
	function jara_menu($mode = "html") {
		global $jconfig;
		$links = array();
		$linknames = array();
		if(strpos($_SERVER["SCRIPT_FILENAME"], "admin/") === false) {
			array_push($linknames, "Homepage");
			array_push($links, "index.php");
			array_push($linknames, "Search");
			array_push($links, "search.php");
			$result = @jara_db_query("select * from jara_pages where menu = '1'");
			if($result) {
				for($i = 0; $i < $result->num_rows; $i++) {
					$row = $result->fetch_assoc();
					array_push($linknames, $row["title"]);
					array_push($links, "page.php?id=".$row["id"]);
				}
			}
		?>
		<?php
			if(!isset($_SESSION["jara_admin"])) {
				array_push($linknames, "Login");
				array_push($links, "login.php");
			}
			else {
				array_push($linknames, "Admin CP");
				array_push($links, "admin/index.php");
				array_push($linknames, "Logout");
				array_push($links, "admin/logout.php");
			}
		}
		else {
			array_push($linknames, "Visit Blog");
			array_push($links, "index.php");
			array_push($linknames, "Overview");
			array_push($links, "admin/index.php");
			if($_SESSION["jara_permissions"][0] == 1) {
				array_push($linknames, "Posts");
				array_push($links, "admin/posts.php");
			}
			if($_SESSION["jara_permissions"][1] == 1) {
				array_push($linknames, "Pages");
				array_push($links, "admin/pages.php");
			}
			if($_SESSION["jara_permissions"][2] == 1) {
				array_push($linknames, "Users");
				array_push($links, "admin/users.php");
			}
			if($_SESSION["jara_permissions"][3] == 1) {
				array_push($linknames, "Upload");
				array_push($links, "admin/upload.php");
			}
			array_push($linknames, "Logout");
			array_push($links, "admin/logout.php");
		}
		$linklist = array_combine($linknames, $links);
		$return = "";
		if($mode == "html") {
			foreach($linklist as $name => $link) {
				$return .= "<a href=\"".$jconfig->settings["blog_url"]."/$link\">$name</a><br />\r\n";
			}
		}
		else if($mode == "list") {
			$return .= "<ul>\r\n";
			foreach($linklist as $name => $link) {
				$return .= "<li><a href=\"".$jconfig->settings["blog_url"]."/$link\">$name</a></li>\r\n";
			}
			$return .= "</ul>";
		}
		return $return;
	}
	
	function jara_post_title($id) {
		$result = jara_db_query("select * from jara_posts where id = '$id'");
		if($result->num_rows == 0) {
			throw new JaraGeneralException("The requested post does not exist.");
		}
		$row = $result->fetch_assoc();
		return $row["title"];
	}

	function jara_page_end() {
		global $jconfig;
		$template = file_get_contents(dirname(__FILE__)."/../templates/".$jconfig->template."/footer.tpl");
		
		$template = preg_replace_callback("/\[if:(pages)\]([^\[]*)\[\/if\]/is", "jara_template_if", $template);
		$template = str_replace("{blog_title}", $jconfig->settings["blog_title"], $template);
		$template = str_replace("{blog_url}", $jconfig->settings["blog_url"], $template);
		$template = str_replace("{menu}", jara_menu(), $template);
		$template = str_replace("{menu.ul}", jara_menu("list"), $template);
		$template = str_replace("{menu.links}", jara_menu_links(), $template);
		$template = str_replace("{menu.links.ul}", jara_menu_links("list"), $template);
		$template = str_replace("{menu.pages}", jara_menu_pages(), $template);
		$template = str_replace("{menu.pages.ul}", jara_menu_pages("list"), $template);
		$template = str_replace("{widgets}", jara_widgets(), $template);
		$template = str_replace("{year}", date("Y"), $template);
		$template = str_replace("{month}", date("F"), $template);
		$template = str_replace("{day}", date("jS"), $template);
		
		echo $template;
	}
?>